import { ROOT, createStorage, getDeviceUuid, httpPost } from "@sker/core";


function setFileLog(name: string) {
    const SD = files.getSdcardPath()
    const root = files.join(SD, 'sker');
    console.setGlobalLogConfig({ file: files.join(root, `${name}.txt`) })
}
/**
 * 执行项目
 * @param path 项目路径
 * @returns 
 */
function execProject(path: string) {
    const packageJson = files.join(path, 'package.json')
    if (files.exists(packageJson)) {
        const project = require(packageJson)
        const mainFile = files.join(path, project.main)
        if (files.exists(mainFile)) {
            engines.all().forEach((item) => {
                if (item.getSource() == mainFile) item.forceStop()
            });
            const script = engines.execScriptFile(mainFile, {
                path: path
            });
            script.getEngine();
            toastLog(`恭喜您，启动成功,${project.name}`)
            return;
        }
        throw new Error(`no ${project.main} exisit`)
    }
    throw new Error(`no package.json exisit`)
}
/**
 * name 应用
 * title 名称
 * icon 图标
 * version 版本号
 * autor 作者
 * url 下载地址  http://xxxx/name-version.zip
 * @param url 
 */
function checkPackage(name: string) {
    const SD = files.getSdcardPath()
    const root = files.join(SD, 'sker');
    files.ensureDir(root)
    const downloadDir = files.join(root, 'downloads')
    files.ensureDir(downloadDir)

    const dirPath = files.join(root, `modules/`)
    files.ensureDir(dirPath)

    const packageInfo = httpPost('client/checkPackage', { name, uuid: getDeviceUuid() })
    const storage = createStorage()
    const version = storage.get(`${name}.version`)
    if (version !== packageInfo.version) {
        toastLog(`存在最新版本${packageInfo.version},正在更新...`)
        // 去下载地址下载
        const download = http.get(packageInfo.url) as AutoJs.Response;
        if (download.statusCode === 200) {
            const filePath = files.join(downloadDir, `${name}-${packageInfo.version}.zip`)
            files.createWithDirs(filePath)
            files.writeBytes(filePath, download.body.bytes())
            toastLog(`下载完成,正在解压并安装...`)
            const zipFile = $zip.open(filePath)
            if (!zipFile.isValidZipFile()) {
                throw new Error(`无效zip文件`)
            }
            if (zipFile.isEncrypted()) {
                throw new Error(`文件已加密`)
            }
            zipFile.extractAll(dirPath)
            storage.put(`${name}.version`, packageInfo.version)
            toastLog(`更新并安装完成`)
            return files.join(dirPath, name);
        }
        throw new Error(`下载失败`)
    } else {
        return files.join(dirPath, `${name}`);
    }
}

try {
    toastLog(`正在检查更新...`)
    // execProject(checkPackage('client'))
    execProject(ROOT)
} catch (e) {
    toastLog(e.toString())
}
